﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace PPCodes.ToolBoxPad
{
    public partial class ConfigureToolBox : Form
    {


        #region 初始化
        
        public ConfigureToolBox()
        {
            InitializeComponent();
        }
        
        public ConfigureToolBox(ToolBoxMain tbm)
        {
            InitializeComponent();
            _tbm = tbm;
        } 
        
             
        private void ConfigureToolBox_Load(object sender, EventArgs e)
        {            
            doc = new XmlDocument();
            doc.Load(configPath);
            LoadCatagories();

            txtEdit.KeyPress += new KeyPressEventHandler(txtEdit_KeyPress);
        }
       
        #endregion


        #region 字段属性
               
        TextBox txtEdit = new TextBox();
        
        private XmlDocument doc;//配置缓存，保存的内存中随时修改，最后按确定时再保存

        static string configPath = @"Config\ControlLibrary.xml";

        int itemSelectedIndex = 0;
        
        private ToolBoxMain _tbm;
        
        private ComponentLibraryLoader _cll;
        private ComponentLibraryLoader cll
        {
            get
            {
                if(_cll==null)
                   _cll= new ComponentLibraryLoader();
                return _cll;
            }
        }



        #endregion


        #region 供外部调用的公共方法

        /// <summary>
        /// 添加新种类
        /// </summary>
        /// <param name="CategoryName"></param>
        /// <returns></returns>
        public bool AddNewCategoryAndRefresh(string CategoryName)
        {
            if (HasSameItemOrIsEmpty(CategoryName))
            {
                return false;
            }
            else
            {
                chklCategories.Items.Add(CategoryName, CheckState.Checked);
                cll.AddNewCategory(doc, CategoryName);  
                chklCategories.Refresh();
                chklCategories.SelectedItem=CategoryName;
                return true;
            }
        }

        /// <summary>
        /// 添加新控件
        /// </summary>
        /// <param name="list"></param>
        /// <returns>为false是表示没有重复值 为true的时候表示忽略了一些重复项</returns>
        public bool AddNewComponentsToGridAndRefresh(List<DataGridViewRow> list)
        {
            bool hasSame=false;
            foreach (DataGridViewRow dr in list)
            {
                if(!HasSameRow(dr))
                {
                  gvComponents.Rows.Add();
                  gvComponents.Rows[gvComponents.Rows.Count-1].Cells["colCheckBox"].Value=true;
                  gvComponents.Rows[gvComponents.Rows.Count-1].Cells["colImage"].Value=dr.Cells["colImage"].Value;
                  gvComponents.Rows[gvComponents.Rows.Count-1].Cells["colName"].Value=dr.Cells["colName2"].Value;
                  gvComponents.Rows[gvComponents.Rows.Count-1].Cells["colNameSpace"].Value=dr.Cells["colNameSpace"].Value;
                  gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colAssembly"].Value = dr.Cells["colAssembly"].Value;
                  gvComponents.Rows[gvComponents.Rows.Count - 1].Tag = dr.Tag;

                  cll.AddComponentToCategory(doc,chklCategories.SelectedItem.ToString(),dr);
                }
                else
                {
                    hasSame=true;
                }
            }
            return hasSame;
        }


        #endregion


        #region 私有方法

        /// <summary>
        /// 加载种类列表
        /// </summary>
        private void LoadCatagories()
        {
            chklCategories.Items.Clear();
            foreach (KeyValuePair<string, bool> ca in cll.GetAllCategories(doc))
            {
                chklCategories.Items.Add(ca.Key, ca.Value);
            }
        }


        private bool HasSameRow(DataGridViewRow dgr)
        {
            foreach (DataGridViewRow dr in gvComponents.Rows)
            {
                if (dgr.Cells["colName2"].Value.ToString() == dr.Cells["colName"].Value.ToString()  &&
                   dgr.Cells["colNameSpace"].Value.ToString() == dr.Cells["colNameSpace"].Value.ToString() &&
                   dgr.Cells["colAssembly"].Value.ToString() == dr.Cells["colAssembly"].Value.ToString())
                {
                    return true;
                }
            }
            return false;
        }

        private bool HasSameItemOrIsEmpty(string name)
        {
            if (String.IsNullOrEmpty(name))
            {
                return true;
            }
            else
            {
                return chklCategories.Items.Contains(name);
            }
        }

        /// <summary>
        /// 选中一个种类时显示所有旗下的控件
        /// </summary>
        private void ShowComonpentsBySelectCategory()
        {
            if (chklCategories.SelectedItem != null)
            {
                gvComponents.Rows.Clear();
                gvComponents.DataSource = null;

                List<ToolBoxItem> list = cll.GetToolsFromCategory(doc, chklCategories.SelectedItem.ToString());

                foreach (ToolBoxItem item in list)
                {
                    gvComponents.Rows.Add();
                    gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colCheckBox"].Value = item.Enabled;
                    gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colImage"].Value = item.Image;
                    gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colName"].Value = item.Name;

                    gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colNameSpace"].Value = item.Namespace;
                    gvComponents.Rows[gvComponents.Rows.Count - 1].Cells["colAssembly"].Value = item.Assembly;
                    ToolComponent toolComponent = new ToolComponent(item.Namespace, new ComponentAssembly(item.Assembly), true);
                    gvComponents.Rows[gvComponents.Rows.Count - 1].Tag = toolComponent;

                }
            } 
            #region 选取除掉做后一个点之后的字符（已废弃）
                //StringBuilder sb = null;                    
                //sb = new StringBuilder();
                //for (int i = 0; i < item.Namespace.Split('.').Length - 1; i++)
                //{
                //    sb.Append(item.Namespace.Split('.')[i]);
                //    sb.Append('.');
                //}
                //sb.Remove(sb.Length - 1, 1); 
                #endregion
        }


        /// <summary>
        /// 保存之前的控件列表的选中状态到配置文件
        /// </summary>
        private void SaveComponentEnableStatus(DataGridViewRow dr)
        {
                cll.SaveComponentEnableStatus(doc, chklCategories.SelectedItem.ToString(), dr);
        }
        
        /// <summary>
        /// 保存当前的空间列表的状态
        /// </summary>
        private void SaveCatagoryEnableStatus()
        {
            for(int i=0;i<chklCategories.Items.Count;i++)
            {
                cll.SaveCategoryEnableStatus(doc, chklCategories.Items[i].ToString(), chklCategories.GetItemChecked(i));
            }
        }


        #endregion


        #region 其他事件

        private void chklCategories_MouseClick(object sender, MouseEventArgs e)
        {
            this.txtEdit.Visible = false;
        }

        /// <summary>
        /// 重命名文本框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtEdit_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)   //Enter键
            {
                cll.RenameCategory(doc, chklCategories.Items[itemSelectedIndex].ToString(), txtEdit.Text.Trim());
                chklCategories.Items[itemSelectedIndex] = txtEdit.Text.Trim();
                LoadCatagories();
                this.txtEdit.Visible = false;
            }
            if (e.KeyChar == 27)   //Esc键
                this.txtEdit.Visible = false;
        }

        /// <summary>
        /// 选中种类显示该种类的工具
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chklCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            //显示新的种类下的控件列表
            ShowComonpentsBySelectCategory();
        }


        /// <summary>
        /// 双击改变选中状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvComponents_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (gvComponents.RowCount > 0 && e.RowIndex != -1)
            {
                if (Convert.ToBoolean(gvComponents.Rows[e.RowIndex].Cells[0].Value))
                {
                    gvComponents.Rows[e.RowIndex].Cells[0].Value = false;
                }
                else
                {
                    gvComponents.Rows[e.RowIndex].Cells[0].Value = true;
                }
            }
        }


        private void gvComponents_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (gvComponents.RowCount > 0)
            {
                //保存之前的控件列表的选中状态到配置文件
                SaveComponentEnableStatus(gvComponents.Rows[e.RowIndex]);
            }
        } 
        #endregion


        #region 菜单及按钮事件

        /// <summary>
        /// 新种类（工具栏按钮）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnNew_Click(object sender, EventArgs e)
        {
            using (NewCategory nc = new NewCategory(this))
            {
                nc.ShowDialog();
            }
        }

        /// <summary>
        /// 删除种类（工具栏按钮）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnRemove_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除吗？", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                cll.RemoveCategory(doc, chklCategories.SelectedItem.ToString());
                chklCategories.Items.RemoveAt(chklCategories.SelectedIndex);
            }
        }

        /// <summary>
        /// 重命名种类（工具栏按钮）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnRename_Click(object sender, EventArgs e)
        {
            itemSelectedIndex = chklCategories.SelectedIndex;
            string itemText = chklCategories.Items[itemSelectedIndex].ToString();
            Rectangle rect = chklCategories.GetItemRectangle(itemSelectedIndex);
            txtEdit.Parent = chklCategories;
            txtEdit.Bounds = rect;
            txtEdit.Multiline = false;
            txtEdit.Size = new System.Drawing.Size(rect.Width, rect.Height);
            txtEdit.Visible = true;
            txtEdit.Text = itemText;
            txtEdit.Focus();
            txtEdit.SelectAll();
        }

        /// <summary>
        /// 新种类（右键菜单）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miNew_Click(object sender, EventArgs e)
        {
            using (NewCategory nc = new NewCategory(this))
            {
                nc.ShowDialog();
            }
        }

        /// <summary>
        /// 删除种类（右键菜单）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除吗？", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                cll.RemoveCategory(doc, chklCategories.SelectedItem.ToString());
                chklCategories.Items.RemoveAt(chklCategories.SelectedIndex);
            }
        }

        /// <summary>
        /// 重命名种类（右键菜单）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miRename_Click(object sender, EventArgs e)
        {
            itemSelectedIndex = chklCategories.SelectedIndex;
            string itemText = chklCategories.Items[itemSelectedIndex].ToString();
            Rectangle rect = chklCategories.GetItemRectangle(itemSelectedIndex);
            txtEdit.Parent = chklCategories;
            txtEdit.Bounds = rect;
            txtEdit.Multiline = false;
            txtEdit.Size = new System.Drawing.Size(rect.Width, rect.Height);
            txtEdit.Visible = true;
            txtEdit.Text = itemText;
            txtEdit.Focus();
            txtEdit.SelectAll();
        }


        /// <summary>
        /// 全部打上勾
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnSelectAll2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvComponents.Rows.Count; i++)
            {
                gvComponents.Rows[i].Cells[0].Value = true;
            }
           
        }


        /// <summary>
        /// 全部取消打勾
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnSelectNo2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvComponents.Rows.Count; i++)
            {
                gvComponents.Rows[i].Cells[0].Value = false;
            }
        }


        /// <summary>
        /// 种类全部打勾
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnSelectAll1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < chklCategories.Items.Count; i++)
            {
                chklCategories.SetItemChecked(i, true);
            }
        }

        /// <summary>
        /// 种类全取消打勾
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnSelectNo1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < chklCategories.Items.Count; i++)
            {
                chklCategories.SetItemChecked(i, false);
            }
        }

        /// <summary>
        /// 往此种类添加控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnAddComponents_Click(object sender, EventArgs e)
        {
            if (chklCategories.SelectedIndex == -1)
            {
                MessageBox.Show("Select a category first");
                return;
            }
            else
            {
                using (AddComponents ac = new AddComponents(this))
                {
                    ac.ShowDialog();
                }
            }
        }

        /// <summary>
        /// 删除选中的控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnRemoveComponents_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvComponents.RowCount > 0 && gvComponents.SelectedRows.Count > 0)
                {
                    for (int i = 0; i < gvComponents.SelectedRows.Count; i++)
                    {
                        cll.RemoveComponentFromCategory(doc, chklCategories.SelectedItem.ToString(), gvComponents.SelectedRows[i]);
                        gvComponents.Rows.Remove(gvComponents.SelectedRows[i]);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// Cancel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// OK
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            SaveCatagoryEnableStatus();

            //保存内存中的配置文件
            doc.Save(configPath);

            //刷新工具栏
            _tbm.LoadToolBox();

            this.Close();
        }
        #endregion



    }
}
